package middleware

import (
	"net/http"
	"simple-crm/config"
	"simple-crm/models"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// AuthMiddleware Session认证中间件
func AuthMiddleware(db *gorm.DB, cfg *config.Config) gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取session
		session := sessions.Default(c)

		// 检查用户是否已登录
		userID := session.Get("user_id")
		if userID == nil {
			c.JSON(http.StatusUnauthorized, gin.H{
				"error": "用户未登录",
			})
			c.Abort()
			return
		}

		// 获取用户信息
		var user models.User
		if err := db.Preload("Roles").First(&user, userID).Error; err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{
				"error": "用户不存在",
			})
			c.Abort()
			return
		}

		// 检查用户状态
		if user.Status != "active" {
			c.JSON(http.StatusUnauthorized, gin.H{
				"error": "用户已被禁用",
			})
			c.Abort()
			return
		}

		// 加载用户权限
		user.LoadPermissions(db)

		// 将用户信息存储到上下文
		c.Set("user", &user)
		c.Set("user_id", user.ID)
		c.Next()
	}
}

// RequireAnyPermission 需要任意一个权限的中间件
func RequireAnyPermission(db *gorm.DB, permissions []string) gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取当前用户
		userInterface, exists := c.Get("user")
		if !exists {
			c.JSON(http.StatusUnauthorized, gin.H{
				"error": "用户未认证",
			})
			c.Abort()
			return
		}

		user, ok := userInterface.(*models.User)
		if !ok {
			c.JSON(http.StatusInternalServerError, gin.H{
				"error": "用户信息错误",
			})
			c.Abort()
			return
		}

		// 检查是否有任意一个权限
		if !user.HasAnyPermission(db, permissions) {
			c.JSON(http.StatusForbidden, gin.H{
				"error": "权限不足",
			})
			c.Abort()
			return
		}

		c.Next()
	}
}
